package com.beadhouse.base.web.controller;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.beadhouse.base.service.UserService;
import com.beadhouse.common.dto.JSONResponse;
import com.beadhouse.common.exeption.BeadHouseException;
import com.beadhouse.entity.UserEntity;

@Controller
public class UserController {
	@Autowired
	UserService userService;
	@GetMapping("/jsp/login")
	public String login() {
		return "login";
	}
	
	@PostMapping("/api/user/login")
	@ResponseBody
	
	public JSONResponse login(
			String account,
			String password,
			HttpServletRequest req
			)  {
		// 2 调用业务方法(进行转换)
		try {
		UserEntity u=userService.login(account, password);
		if(u!=null) {
			HttpSession session = req.getSession(false);
			if (session != null) {
				// 说明之前访问过
				session.invalidate();
			}
			session = req.getSession(true);
			session.setAttribute(UserEntity.class.getName(), u);
		}
			
		}catch(BeadHouseException e) {
			return JSONResponse.fail(e);
		}
		catch (Exception e) {
			
			e.printStackTrace();
		}
		// 3把当前登录用户上下文放入session中
		return JSONResponse.ok();
	}
	@GetMapping("/jsp/logout")
	public String logout(HttpServletRequest req) {
		HttpSession  session=req.getSession();
		session.invalidate();
		return "login";
	}
}
